package postgres

import (
	"context"
	"errors"
	"quipus/internal/database/model"
	apb "quipus/proto/gen/assist"

	_ "github.com/jackc/pgx/v5/stdlib"
	_ "github.com/joho/godotenv/autoload"
)

func (p *PGDB) CreateWebhook(ctx context.Context, create *model.Webhook) error {
	p.query()
	webhook := q.WithContext(ctx).Webhook
	err := webhook.Create(create)
	if err != nil {
		return err
	}

	return nil
}

func (p *PGDB) ListWebhooks(ctx context.Context, find *apb.FindWebhook) ([]*model.Webhook, error) {
	p.query()
	webhook := q.WithContext(ctx).Webhook

	if find.Id > 0 {
		webhook = webhook.Where(q.Webhook.ID.Eq(find.Id))
	}
	if find.CreatorId > 0 {
		webhook = webhook.Where(q.Webhook.CreatorID.Eq(find.CreatorId))
	}

	return webhook.Find()
}

func (p *PGDB) GetWebhook(ctx context.Context, find *apb.FindWebhook) (*model.Webhook, error) {
	p.query()
	webhook := q.WithContext(ctx).Webhook

	if find.Id > 0 {
		webhook = webhook.Where(q.Webhook.ID.Eq(find.Id))
	}
	if find.CreatorId > 0 {
		webhook = webhook.Where(q.Webhook.CreatorID.Eq(find.CreatorId))
	}

	return webhook.First()
}

func (p *PGDB) UpdateWebhook(ctx context.Context, update *apb.UpdateWebhook) (*model.Webhook, error) {
	p.query()
	webhook := q.WithContext(ctx).Webhook
	updateValue := &model.Webhook{}

	if update.Id <= 0 {
		return nil, errors.New("id is required")
	}

	updateValue.ID = update.Id
	if update.RowStatus > 0 {
		updateValue.RowStatus = update.RowStatus.String()
	}
	if len(update.Name) > 0 {
		updateValue.Name = update.Name
	}
	if update.Url != "" {
		updateValue.URL = update.Url
	}
	_, err := webhook.Updates(updateValue)
	return updateValue, err
}

func (p *PGDB) DeleteWebhook(ctx context.Context, delete *apb.DeleteWebhook) error {
	p.query()
	webhook := q.WithContext(ctx).Webhook

	if delete.Id > 0 {
		webhook = webhook.Where(q.Webhook.ID.Eq(delete.Id))
	}
	_, err := webhook.Delete()
	return err
}
